<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { addUser,getUser,deleteUser,putUser,getUserRole,getRole,putUserRole } from '@/api/index';
import inputtext from '@/components/inputs/inputtext.vue';
import uploadfile from '@/components/inputs/uploadfile.vue';
import type { FormInstance, FormRules } from 'element-plus'
import { useRoute } from 'vue-router';
const route =useRoute()
onMounted(()=>{
  console.log(route)
  getData();
})
// 初始化数据
const tableData:any[] = reactive([]);
const getData = async function(){
  let res = await getUser();
  tableData.length = 0;
  tableData.push(...res.data.data as any[]);
}
// 选中行
const selectRow:any[] = reactive([]);
const getSelectionRows = function(e:any){
    selectRow.length = 0
    selectRow.push(...e);
}

// ref表格绑定
const eltable:any = ref(null);

// 批量删除
const deleteRow =async function(){
  let deleteid:string[] = [];
  selectRow.forEach((e:any)=>{
    deleteid.push(e.id);
  })
  await deleteUser(deleteid.toString());
  getData();
}

// 单条删除
const deleteOneRow =async function(id:number){
  await deleteUser([id].toString());
  getData();
}

//#region  新增数据
const addshow = ref(false)
const addruleFormRef = ref<FormInstance>()
interface Ruleform {
  username:string
  password:string
  avatar:any
  phone:string
}
const addform=reactive<Ruleform>({
  username:'',
  password:'',
  avatar:[],
  phone:'',
})
// 表单校验
const addrules = reactive<FormRules<Ruleform>>({
  username:[
    {required:true,message:'必填项！',trigger: 'blur'},
    {min:2,max:15,message:'用户名长度2-15',trigger: 'blur'}
  ],
  password:[
    {required:true,message:'必填项',trigger: 'blur'},
    {min:5,max:20,message:"密码长度5-20",trigger: 'blur'}
  ],
  avatar:[
    {required:true,message:'上传头像',trigger: 'blur'}
  ],
  phone:[
    {required:true,message:'必填项',trigger: 'blur'},
    {min:11,max:11,message:'手机号长度11',trigger: 'blur'}
  ]
})
const addsubmitform =async function(formref:FormInstance|undefined){
  if(!formref) return;
  await formref.validate((valid,fields)=>{
    if(valid){
      addshow.value = false;
      const data = {
        username:addform.username,
        password:addform.password,
        phone:addform.phone,
        avatar:addform.avatar[0].response
      }
      addUser(data).then(res=>{
        console.log(res)
        addshow.value = false
        getData();
      })      
    }else{
      console.log(fields)
    }
  })
  addform.avatar = []
  addform.password = ''
  addform.phone = ''
  addform.username = ''
}

//#endregion

//#region  修改表单数据
const updateshow = ref(false)
const rowid:any = ref()
const updateshowdialog = function(id:number){
  updateshow.value = true
  rowid.value = id
}
const updateruleFormRef=ref<FormInstance>();
const updateform=reactive<Ruleform>({
  username:'',
  password:'',
  avatar:[],
  phone:'',
})

const updaterules = reactive<FormRules<Ruleform>>({
  username:[
    {min:2,max:15,message:'用户名长度2-15',trigger: 'blur'}
  ],
  password:[
    {min:5,max:20,message:"密码长度5-20",trigger: 'blur'}
  ],
  phone:[
    {min:11,max:11,message:'手机号长度11',trigger: 'blur'}
  ]
})

const updatesubmitform =async function(formref:FormInstance|undefined){
  if(!formref) return;
  await formref.validate((valid)=>{
    if(valid){
      addshow.value = false;
      const data:any = {};
      if(updateform.username){
        data["username"] = updateform.username
      }
      if(updateform.password) {
        data["password"] = updateform.password
      }
      if(updateform.phone){
        data["phone"] = updateform.phone
      }
      if(updateform.avatar.length>0){
        data["avatar"] = updateform.avatar[0].response
      }
      putUser(rowid.value,data).then(res=>{
        console.log(res);
        getData();
      })      
    }
    updateshow.value = false
  })
  updateform.avatar = [];
  updateform.password = '';
  updateform.phone = '';
  updateform.username='';
}
//#endregion

/////////////////////////////////////////////////////
// 用户 角色绑定
const userroleshow = ref<boolean>(false)
const userid = ref<number>(0)
const roles = reactive<any[]>([])
const selectroles = ref<any[]>([])
const handleuserrole = async function(id:number|string){
  selectroles.value = [];
  roles.length = 0
  userid.value = Number(id);
  userroleshow.value = true;
  let res = await getRole();
  roles.push(...res.data.data)
  res = await getUserRole(id);
  for(let i =0;i<res.data.data.length;i++){
    selectroles.value.push(res.data.data[i].role_id)
  }
}
const changeUserRole = async function() {
  console.log(selectroles.value)
  await putUserRole(userid.value,selectroles.value);
  userroleshow.value = false
}
</script>

<template>
    <div class="user">
        <div class="tablebtn">
            <el-button size="small" @click="addshow=true" type="primary" v-if="route.meta.add">新增</el-button>
            <el-button size="small" type="danger" @click="deleteRow" v-if="route.meta.deletes">批量删除</el-button>
        </div>
        <div style="width: 100%;height: calc(100% - 70px);">
          <el-table
          ref = 'eltable'
          :data="tableData" 
          style="width: 100%;height: 100%;" 
          stripe 
          border 
          highlight-current-row 
          table-layout="auto"
          size="small"
          @selection-change="getSelectionRows"
          >
            <el-table-column fixed type="selection" width="55" align="center"></el-table-column>
            <el-table-column type="index" label="序号" width="55" align="center"></el-table-column>
            <el-table-column prop="username" label="用户名" align="center" />
            <el-table-column prop="password" label="密码" align="center" />
            <el-table-column prop="phone" label="手机号" align="center" />
            <el-table-column prop="avatar" label="头像" align="center"></el-table-column>
            <el-table-column prop="status" label="状态"  align="center">
              <template #default="scope">
                <el-button disabled size="small" :type="scope.row.status == 1?'primary':'warning'">
                  {{ scope.row.status == 1?'启用':'禁用'  }}
                </el-button>
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="200">
              <template #default="scope">
                <el-button size="small" @click="handleuserrole(scope.row.id)" v-if="route.meta.auth">权限</el-button>
                <el-button size="small" @click="updateshowdialog(scope.row.id)" v-if="route.meta.update">修改</el-button>
                <el-button size="small" @click="deleteOneRow(scope.row.id)" v-if="route.meta.delete"> 删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="tablepag" v-if="false">
            <el-pagination
                small
                background
                layout="prev, pager, next"
                :total="50"
                class="mt-4"
            />
        </div>
        <!-- 新增用户 -->
        <el-dialog v-model="addshow" style="width: 600px" >
          <template #header>
            新增
          </template>
            <el-form ref="addruleFormRef" :rules="addrules" :model="addform" :label-width="70">
              <inputtext prop="username" label="用户名" v-model.trim="addform.username"></inputtext>
              <inputtext prop="password" label="密码" v-model.trim="addform.password"></inputtext>
              <inputtext prop="phone" label="手机号" v-model.trim="addform.phone"></inputtext>
              <uploadfile prop="avatar" label="头像" :upload="{multiple:false,limit:1,action:'index.php/Upload/uploadAvatar',accept:'.jpg,.jpeg,.png,.webp'}" v-model.trim="addform.avatar"></uploadfile>
            </el-form>
            <template #footer>
                <el-button @click="addsubmitform(addruleFormRef)">新增</el-button>
                <el-button @click="addshow=false">取消</el-button>
              </template>
        </el-dialog>
        <!-- update -->
        <el-dialog v-model="updateshow" style="width: 600px" draggable>
            <template #header>
              修改
            </template>
            <el-form ref="updateruleFormRef" :rules="updaterules" :model="updateform" :label-width="70">
              <inputtext prop="username" label="用户名" v-model.trim="updateform.username"></inputtext>
              <inputtext prop="password" label="密码" v-model.trim="updateform.password"></inputtext>
              <inputtext prop="phone" label="手机号" v-model.trim="updateform.phone"></inputtext>
              <uploadfile prop="avatar" label="头像" :upload="{multiple:false,limit:1,action:'/upload',accept:'.jpg,.jpeg,.png,.webp'}" v-model.trim="updateform.avatar"></uploadfile>
            </el-form>
            <template #footer>
                <el-button @click="updatesubmitform(updateruleFormRef)">修改</el-button>
                <el-button @click="updateshow=false">取消</el-button>
              </template>
        </el-dialog>

        <el-dialog v-model="userroleshow" draggable>
          <template #header> 权限控制 </template>
          <el-select v-model="selectroles" multiple placeholder="选择角色">
            <el-option v-for="item in roles" :label="item.rolename" :value="item.id" :key="item.id" />
          </el-select>
          <template #footer>
            <el-button @click="changeUserRole">确认</el-button>
            <el-button @click="userroleshow = false">取消</el-button>
          </template>
        </el-dialog>
    </div>


</template>

<style>
.user{
    width: 100%;
    height: 100%;
}
.tablebtn{
    width:100%;
    height:40px;
    display:flex;
    align-items:center;
    background:rgba(123,123,123,0.2);
    padding-left:20px;
    box-sizing: border-box;
}
.tablepag{
    width:100%;
    height:30px;
    background:rgba(123,123,123,0.2);
    display:flex;
    align-items:center;
    justify-content: center;
}
</style>